package com.pingpang.controller;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pingpang.util.ImageUtil;
 
@RestController
@RequestMapping("/fileUpload")
public class PictureController{
	@ResponseBody
    @RequestMapping("/imageUpload")
    //名字upload是固定的，有兴趣，可以打开浏览器查看元素验证
    public String imageUpload(HttpServletRequest request,@RequestParam("file") MultipartFile file) throws Exception {
		//获取跟目录
		File path = new File(ResourceUtils.getURL("file:").getPath());
		if(!path.exists()) path = new File("");
		System.out.println("path:"+path.getAbsolutePath());

		//如果上传目录为/static/images/upload/，则可以如下获取：
		File upload = new File(path.getAbsolutePath(),"static/upload/");
		if(!upload.exists()) upload.mkdirs();
		System.out.println("upload url:"+upload.getAbsolutePath());
		
		System.out.println(request.getServletContext().getRealPath("/static/upload"));
		
		// 获取文件名0
        String fileName = file.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //实际处理肯定是要加上一段唯一的字符串（如现在时间），这里简单加 cun
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        String newFileName = uuid + suffixName;
        //使用架包 common-io实现图片上传
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(upload.getAbsolutePath()+File.separator + newFileName));
         
        //再保存一份压缩文件 
        String reImg=uuid+ suffixName;
        
        if(PictureController.isImage(upload.getAbsolutePath()+File.separator + newFileName)) {
        	reImg=uuid+"_2"+ suffixName;
        	ImageUtil.resize(new File(upload.getAbsolutePath()+File.separator + newFileName), new File(upload.getAbsolutePath()+File.separator + reImg),150, 0.7f);
        }
        
        //实现图片回显，基本上是固定代码，只需改路劲即可
        Map<String,Object> resultMap=new HashMap<String,Object>();
        Map<String,Object> fileMap=new HashMap<String,Object>();
        resultMap.put("code", "0");
        resultMap.put("msg", "上传成功");
        resultMap.put("data", fileMap);
        fileMap.put("src", request.getContextPath()+File.separator +"upload/"+ reImg);
        fileMap.put("title", newFileName);
        ObjectMapper mapper = new ObjectMapper();
        String result=mapper.writeValueAsString(resultMap);
        return result;
    }
	
	public static boolean isImage(String srcFileName) {
		FileInputStream imgFile = null;
		byte[] b = new byte[10];
		int l = -1;
		try {
			imgFile = new FileInputStream(srcFileName);
			l = imgFile.read(b);
			imgFile.close();
		} catch (Exception e) {
			return false;
		}
		if (l == 10) {
			byte b0 = b[0];
			byte b1 = b[1];
			byte b2 = b[2];
			byte b3 = b[3];
			byte b6 = b[6];
			byte b7 = b[7];
			byte b8 = b[8];
			byte b9 = b[9];
			if (b0 == (byte) 'G' && b1 == (byte) 'I' && b2 == (byte) 'F') {
				return true;
			} else if (b1 == (byte) 'P' && b2 == (byte) 'N' && b3 == (byte) 'G') {
				return true;
			} else if (b6 == (byte) 'J' && b7 == (byte) 'F' && b8 == (byte) 'I' && b9 == (byte) 'F') {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	
	@ResponseBody
    @RequestMapping("/audioUpload")
    //名字upload是固定的，有兴趣，可以打开浏览器查看元素验证
    public String audioUpload(HttpServletRequest request,@RequestParam("file") MultipartFile file) throws Exception {
		//获取跟目录
		File path = new File(ResourceUtils.getURL("'file:").getPath());
		if(!path.exists()) path = new File("");
		System.out.println("path:"+path.getAbsolutePath());

		//如果上传目录为/static/images/upload/，则可以如下获取：
		File upload = new File(path.getAbsolutePath(),"/static/upload/");
		if(!upload.exists()) upload.mkdirs();
		System.out.println("upload url:"+upload.getAbsolutePath());
		
		System.out.println(request.getServletContext().getRealPath("/static/upload"));
		
		String suffixName=".wav";
        //实际处理肯定是要加上一段唯一的字符串（如现在时间），这里简单加 cun
        String uuid = UUID.randomUUID().toString().replace("-", "").toLowerCase();
        String newFileName = uuid + suffixName;
        //使用架包 common-io实现图片上传
        FileUtils.copyInputStreamToFile(file.getInputStream(), new File(upload.getAbsolutePath()+File.separator + newFileName));
         
        //再保存一份压缩文件 
        String reImg=uuid+ suffixName;
        
        //实现图片回显，基本上是固定代码，只需改路劲即可
        Map<String,Object> resultMap=new HashMap<String,Object>();
        Map<String,Object> fileMap=new HashMap<String,Object>();
        resultMap.put("code", "0");
        resultMap.put("msg", "上传成功");
        resultMap.put("data", fileMap);
        fileMap.put("src", request.getContextPath()+File.separator +"upload/"+ reImg);
        fileMap.put("title", newFileName);
        ObjectMapper mapper = new ObjectMapper();
        String result=mapper.writeValueAsString(resultMap);
        return result;
	}
}